<template>
  <a-spin :spinning="spinning">
    <BaseContainer>
      <!-- 隐藏GEO拓词工具和下载文件功能 -->
      <!--
      <p style="position: fixed; top: 9%; right: 12%; font-weight: 700; font-size: 18px">
        <a href="http://geotc.e-baixing.com/" target="_blank">GEO拓词工具</a>
      </p>
      <p
        style="position: fixed; top: 9%; right: 4%; cursor: pointer; color: red; font-weight: 700; font-size: 18px"
        @click="downloadTemplate"
      >
        <DownloadOutlined style="margin-right: 4px" />
        下载文件
      </p>
      -->
      <QueryFilter
        :model="queryFields"
        :label-col="{ style: { width: '70px' } }"
        @submit="queryOrderList"
        @reset="resetOrderList"
      >
        <a-form-item name="orderId" label="词包id">
          <a-input v-model:value.trim="queryFields.orderId" placeholder="请输入词包ID" allow-clear />
        </a-form-item>
        <a-form-item name="priceAskId" label="查价id">
          <a-input v-model:value.trim="queryFields.priceAskId" placeholder="请输入查价ID" allow-clear />
        </a-form-item>
        <a-form-item name="orderNo" label="订单编号">
          <a-input v-model:value.trim="queryFields.orderNo" placeholder="请输入订单编号" allow-clear />
        </a-form-item>
        <a-form-item name="platformNames" label="平台">
          <a-input placeholder="请输入平台名称" allow-clear v-model:value.trim="queryFields.platformNames"></a-input>
        </a-form-item>
        <a-form-item name="keyword" label="关键词">
          <a-input placeholder="请输入准确的关键词" allow-clear v-model:value.trim="queryFields.keyword"></a-input>
        </a-form-item>
        <a-form-item name="customerId" label="客户id">
          <a-input v-model:value.trim="queryFields.customerId" placeholder="请输入客户ID" allow-clear />
        </a-form-item>
        <a-form-item name="proxyName" label="代理商">
          <a-input v-model:value="queryFields.proxyName" placeholder="请输入代理商" allow-clear />
        </a-form-item>
        <a-form-item name="comboPriceName" label="订单时长">
          <a-select
            v-model:value="queryFields.comboPriceName"
            placeholder="请选择订单时长"
            :options="comboPriceOptions"
          />
        </a-form-item>
        <a-form-item name="customerName" label="客户名称">
          <a-input placeholder="请输入客户名称" allow-clear v-model:value.trim="queryFields.customerName"></a-input>
        </a-form-item>
        <a-form-item name="comboName" label="购买套餐">
          <a-input v-model:value.trim="queryFields.comboName" placeholder="请输入购买套餐" allow-clear />
        </a-form-item>
        <a-form-item name="sellerName" label="销售员">
          <a-input placeholder="请输入销售员" allow-clear v-model:value.trim="queryFields.sellerName"></a-input>
        </a-form-item>
        <!--<a-form-item name="payStatus" label="状态">
        <a-select v-model:value="queryFields.payStatus" placeholder="请选择状态" :options="payStatusOptions" />
      </a-form-item>-->
        <a-form-item name="serviceStatus" label="投放状态">
          <a-select
            v-model:value="queryFields.serviceStatus"
            placeholder="请选择投放状态"
            :options="serviceStatusOptions"
          />
        </a-form-item>
        <a-form-item name="type" label="类型">
          <a-select v-model:value="queryFields.type" placeholder="请选择类型" :options="typeOptions" />
        </a-form-item>
        <a-form-item name="industryId" label="行业">
          <industry-cascader
            v-model:industry-id="industryId"
            :industry-list="industryList"
            @change="handleIndustryChange"
          />
        </a-form-item>
        <a-form-item name="productId" label="产品">
          <a-select
            allowClear
            v-model:value="queryFields.productId"
            placeholder="请选择产品"
            :options="productOptions"
          />
        </a-form-item>
        <a-form-item name="productId" label="大区">
          <a-select allowClear v-model:value="queryFields.organize" placeholder="请选择大区">
            <a-select-option value="东南区">东南区</a-select-option>
            <a-select-option value="总部">总部</a-select-option>
            <a-select-option value="东区">东区</a-select-option>
            <a-select-option value="南区">南区</a-select-option>
            <a-select-option value="北区">北区</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item name="productId" label="购买时间">
          <a-date-picker
            class="w-full"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            v-model:value="queryFields.buyTime"
            placeholder="请选择购买时间"
          />
        </a-form-item>
        <a-form-item label="表格列">
          <a-select
            v-model:value="selectedFields"
            mode="multiple"
            allowClear
            placeholder="请选择要展示的列"
            :options="columnOptions"
          />
        </a-form-item>
      </QueryFilter>

      <Divider />

      <table-toolbar title="订单列表">
        <export-excel-group
          group
          :loading="excelLoading"
          :col="columns"
          :data="tableData"
          v-permission="[OPERATION]"
          @on-export="handleExportExcel"
          @on-export-all="handleExportExcelAll"
        />
      </table-toolbar>
      <a-table
        :loading="loading"
        table-layout="fixed"
        row-key="id"
        :pagination="pagination"
        :columns="dynamicColumns"
        :data-source="tableData"
        :scroll="{ x: 1000 }"
        @change="handleTableChange"
      >
        <template #bodyCell="{ record, column, text }">
          <template v-if="column.key === 'tpType'">
            <a-tooltip placement="topLeft">
              <template #title>
                {{ record.tpType }}
              </template>
              <span class="over-hidden">{{ record.tpType || '--' }}</span>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'tpNotes'">
            <a-tooltip placement="topLeft">
              <template #title>
                {{ record.tpNotes }}
              </template>
              <span class="over-hidden">{{ record.tpNotes || '--' }}</span>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'createTime'">
            {{ formatDate(text) }}
          </template>
          <template v-if="column.key === 'type'">
            {{ TypeKeyMap[text] }}
          </template>

          <template v-if="column.key === 'marketPrice'"> {{ text || '--' }} </template>
          <template v-if="column.key === 'orderPrice'"> {{ text || '--' }} </template>

          <template v-if="column.key === 'soldAreas'">
            <area-popover ellipsis :areas="text" :product-id="record.productId" />
          </template>
          <template v-if="column.key === 'orderNo'">
            <span class="cursor-pointer" v-clipboard="record.orderNo" v-clipboard:success="copySuccess">{{
              record.orderNo
            }}</span>
          </template>
          <template v-if="column.key === 'hzNotes'">
            <a-tooltip placement="topLeft">
              <template #title>
                {{ record.hzNotes }}
              </template>
              <span class="over-hidden">{{ record.hzNotes }}</span>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'priceAskId'">
            <span class="cursor-pointer" v-clipboard="record.priceAskId" v-clipboard:success="copySuccess">{{
              record.priceAskId
            }}</span>
          </template>

          <template v-if="column.key === 'isCancel'">
            {{ record.isCancel === 0 ? '无' : '有' }}
          </template>

          <template v-if="column.key === 'excelUrl'">
            {{ record.excelUrl == null ? '未上传' : '已上传' }}
          </template>

          <template v-if="column.key === 'id'">
            <span
              class="cursor-pointer"
              v-if="record.oldOrderId"
              v-clipboard="record.oldOrderId"
              v-clipboard:success="copySuccess"
              >续费词包：{{ record.oldOrderId }}</span
            >
            <span class="cursor-pointer" v-else v-clipboard="record.id" v-clipboard:success="copySuccess">{{
              record.id
            }}</span>
          </template>
          <template v-if="column.key === 'orderWordsStr'">
            <a-tooltip placement="topLeft">
              <template #title>
                {{ record.orderWordsStr }}
              </template>
              <span class="cursor-pointer" v-clipboard="record.orderWordsStr" v-clipboard:success="copySuccess">{{
                record.orderWordsStr
              }}</span>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'serviceTime'">
            <div style="display: flex">
              <a-range-picker
                :value="[record.startTime, record.endTime]"
                show-time
                valueFormat="YYYY-MM-DD HH:mm:ss"
                :disabled="true"
              />
            </div>
          </template>
          <template v-if="column.key === 'operate'">
            <a-button @click="handleDetail(record)">详情</a-button>
            <a-button v-permission="[OPERATION]" class="ml-2" @click="openOnlineEdit(record)">编辑</a-button>

            <a-dropdown>
              <template #overlay>
                <a-menu @click="handleMenuClick($event, record)">
                  <a-menu-item key="1"> 退全款 </a-menu-item>
                  <a-menu-divider></a-menu-divider>
                  <a-menu-item key="2"> 退剩余 </a-menu-item>
                </a-menu>
              </template>
              <a-button danger class="ml-2" v-permission="[OPERATION]" :disabled="handleRefundDisabled(record)">
                退款
                <DownOutlined />
              </a-button>
            </a-dropdown>
            <a-dropdown>
              <a-button class="ml-2"
                >更多
                <DownOutlined />
              </a-button>
              <template #overlay>
                <a-menu>
                  <!--   <a-menu-item>
                    <a-button :loading="shopLoadings" @click="goShop(record)">钻石店铺</a-button>
                  </a-menu-item>
                   <a-menu-item>
                  <a-button :loading="shopLoadings" @click="jump(record)">百姓店铺</a-button>
                </a-menu-item>
                <a-menu-item>
                  <a-button :loading="shopLoading" @click="jumps(record)">百搜店铺</a-button>
                </a-menu-item> -->
                  <!-- v-permission="[SALES]"  :disabled="renewalDisabled(record)" && record.status !== 3-->

                  <a-menu-item>
                    <a-button @click="openAirReport(record)" :disabled="!record.id"> 数据报表 </a-button>
                  </a-menu-item>

                  <a-menu-item>
                    <a-button v-permission="[OPERATION]" @click="openLinkEdit(record)">设置链接</a-button>
                  </a-menu-item>
                  <a-menu-item>
                    <a-button @click="openexcel(record)">上传压缩包</a-button>
                  </a-menu-item>
                  <a-menu-item>
                    <a-button @click="openexcels(record)">下载压缩包</a-button>
                  </a-menu-item>
                  <!-- 隐藏设置账号密码、查看账号密码、优化资料提交按钮 -->
                  <!--
                  <a-menu-item>
                    <a-button v-permission="[OPERATION]" @click="namepwd(record)">设置账号密码</a-button>
                  </a-menu-item>
                  <a-menu-item>
                    <a-button v-permission="[OPERATION]" @click="namepwdshows(record)">查看账号密码</a-button>
                  </a-menu-item>
                  <a-menu-item>
                    <a-button @click="submitInfo(record)">优化资料提交</a-button>
                  </a-menu-item>
                  -->
                  <!--                  <a-menu-item v-if="record.productId != 3 && record.productId != 9">-->
                  <!--                    <a-button style="width: 90px" @click="handleRenewal(record)"> 续费 </a-button>-->
                  <!--                  </a-menu-item>-->
                </a-menu>
              </template>
            </a-dropdown>

            <!-- <a-button style="margin-left: 10px" v-if="record.productId === 7" type="primary" @click="handleDetail(record)"
            >加购</a-button
          > -->
          </template>
        </template>
      </a-table>
      <!-- <OrderRenewal v-model:show="renewalDialog.visible" :data="renewalData" :caling="caling" :loading="renewalLoading"
      :submitting="submitting || bwSubmitting" v-model:order-keyword="orderKeyword" :order-keyword="orderKeyword"
      @on-change="handleRenewalChange" @on-submit="handleSubmit" /> -->
      <OrderRenewal
        v-model:show="renewalDialog.visible"
        :data="renewalData"
        :caling="caling"
        :loading="renewalLoading"
        :submitting="submitting || bwSubmitting"
        v-model:order-keyword="currentOrderKeywords"
        @on-change="handleRenewalChange"
        @on-submit="handleSubmit"
        :orderId="oldOrderId()"
        @on-reset="handleRenewalReset"
      />
    </BaseContainer>
  </a-spin>
  <a-modal v-model:visible="shopVisible" style="top: 40px" width="1400px" title="钻石店铺">
    <LandingPage :loadOption="loadOption"></LandingPage>
    <template #footer>
      <a-button key="back" @click="shopVisible = false">关闭</a-button>
    </template>
  </a-modal>
  <OrderAddLink
    v-model:visible="linkForm.visible"
    :value="linkForm.value"
    :orderId="linkForm.orderId"
    @refresh="refreshLinkFn"
  ></OrderAddLink>

  <OrderOnline
    v-model:visible="onlineForm.visible"
    :value="onlineForm.value"
    :orderId="onlineForm.orderId"
    :orderStatus="onlineForm.orderStatus"
    :notes="onlineForm.notes"
    @refresh="refreshOnLineFn"
  ></OrderOnline>

  <a-modal v-model:visible="excelForm.visible" :footer="null" @cancel="closeExcelModal">
    <template #title>
      <div class="flex justify-between items-center">
        <span>上传文件</span>
      </div>
    </template>
    <div style="text-align: center; color: red">上传资料请上传压缩包，压缩包内需要包含下载填写的exel以及图片文件</div>
    <div class="mb-4" style="margin-top: 10px">
      <a-upload
        :before-upload="() => false"
        :show-upload-list="false"
        :multiple="false"
        :accept="'.xlsx, .xls, .zip, .rar, .7z'"
        @change="handleFileChange"
      >
        <a-button :loading="loadings" type="primary">选择文件</a-button>
      </a-upload>
      <div v-if="excelForm.file" class="mt-2 text-sm text-gray-600">已选择文件: {{ excelForm.file.name }}</div>
    </div>
    <div class="flex justify-end">
      <a-button @click="closeExcelModal" class="mr-2">取消</a-button>
      <a-button :loading="loadings" type="primary" @click="handleUploadExcel" :disabled="!excelForm.file">
        上传文件
      </a-button>
    </div>
  </a-modal>

  <div>
    <a-modal v-model:visible="visiblenamepwe" title="设置账号密码" @ok="handleOk">
      <a-form :model="formStatenampwe" name="basic" layout="vertical" autocomplete="off">
        <a-form-item label="账号" name="username" :rules="[{ required: true, message: '账号不能为空' }]">
          <a-input v-model:value="formStatenampwe.username" />
        </a-form-item>

        <a-form-item label="密码" name="pwd" :rules="[{ required: true, message: '密码不能为空' }]">
          <a-input-password v-model:value="formStatenampwe.pwd" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>

  <div>
    <a-modal v-model:visible="visibleshows" title="查看账号密码" @ok="handleOkshows">
      <div>账号:{{ usernameshows }}</div>
      <div>密码:{{ pwdshows }}</div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router'
import { KeywordData } from '@/services/order/getOrderKeyword'
import { computed, onActivated, onMounted, onUnmounted, reactive, ref } from 'vue'
import { formatDate, toLabelValue } from '@/utils'
import { BwComboPriceNameKeyMap } from '@/views/price-sheet/interface'
import { message, Modal, type TableProps } from 'ant-design-vue'
import getOrderList, { getOrderListWithAll, type OrderQuery } from '@/services/order/getOrderList'
import { useMainStore } from '@/store/useMainStore'
import { compact, isNil, omit } from 'lodash-es'
import { useOrderStore } from '@/store/useOrderStore'
import { hasPermission } from '@/utils/permission'
import TableToolbar from '@/components/table-toolbar/index.vue'
import postRefundPartOrder from '@/services/order/postRefundPartOrder'
import postRefundAllOrder from '@/services/order/postRefundAllOrder'
import BaseContainer from '@/components/base-container/index.vue'
import QueryFilter from '@/components/query-filter/index.vue'
import Divider from '@/components/divider/index.vue'
import AreaPopover from '@/components/area-popover/index.vue'
import OrderRenewal from '@/views/order/components/OrderRenewal.vue'
import OrderAddLink from '@/views/order/components/OrderAddLink.vue'
import OrderOnline from '@/views/order/components/OrderOnline.vue'
import getOrderRenewal from '@/services/order/getOrderRenewal'
import calRenewalPrice from '@/services/order/calRenewalPrice'
import createPriceSheet from '@/services/price-sheet/createPriceSheet'
import { usePriceSheetStore } from '@/store/usePriceSheetStore'
import { priceTable } from '@/shared/priceTable'
import getOrderKeyword from '@/services/order/getOrderKeyword'
import orderKeywordByGetitem from '@/services/order/orderKeywordByGetitem'
import type { Order } from '@/core/interfaces/order'
import { PayStatusKeyMap, ServiceStatusKeyMap } from '@/core/mapper/status'
import { ApproveStatusEnum, PayStatusEnum, ServiceStatusEnum } from '@/core/enums/status'
import { ChannelTypeEnum, PayTypeEnum, TypeEnum, LandingPageEnum, IsFromHjzwEnum, IsTPEnum } from '@/core/enums/type'
import { AuthEnum } from '@/core/enums/auth'
import { ComboPriceNameEnum, ComboPriceTimer } from '@/core/enums/name'
import { PlatformEnum, ProductEnum } from '@/core/enums/platform'
import { PayTypeKeyMap, TypeKeyMap } from '@/core/mapper/type'
import { PlatformKeyMap } from '@/core/mapper/platform'
import ExportExcelGroup from '@/components/export-excel-group/index.vue'
import { bwPriceDataParser } from '@/core/parser/priceDataParser'
import { fromZodError } from 'zod-validation-error'
import { DownOutlined } from '@ant-design/icons-vue'
import { useReloadModal } from '@/hooks/useReloadModal'
import createBwPriceSheet from '@/services/price-sheet/createBwPriceSheet'
import IndustryCascader from '@/components/industry-cascader/index.vue'
import getIndustryList from '@/services/order/getIndustryList'
import getShopUrl from '@/services/order/getShopUrl'
import getShopUrls from '@/services/order/getBxShopCustomerPhone'
import MD5 from 'crypto-js/md5'
import getRenewPrice from '@/services/account-management/getRenewPrice'
import LandingPage from '@/views/other/LandingPage.vue'
import getProductList from '@/services/order/getProductList'
import { h } from 'vue'
import orderupFile from '@/services/account-management/orderupFile'
import ordersetExcelUr from '@/services/account-management/ordersetExcelUr'
import setUserPwd from '@/services/account-management/setUserPwd'
import PromotionUpdateTime from '@/views/promotion/components/PromotionUpdateTime.vue'
import { DownloadOutlined } from '@ant-design/icons-vue'
defineOptions({
  name: 'OrderManager'
})
useReloadModal()
const router = useRouter()
const mainStore = useMainStore()
const orderStore = useOrderStore()
const priceSheetStore = usePriceSheetStore()
const { AGENT, AGENT_BOSS, SALES, OPERATION, ADMIN } = AuthEnum
const currentRecord = reactive<Partial<Order>>({})
const typeOptions = ref(toLabelValue(TypeKeyMap))
const productOptions = ref()
const serviceStatusOptions = ref(toLabelValue(omit(ServiceStatusKeyMap, ServiceStatusEnum.PENDING)))
const renewalDialog = reactive({
  visible: false
})
const industryId = ref<number>()
const keywords = ref([])
//
const handleKeywordUpdate = (newKeywords) => {
  keywords.value = newKeywords
}
const comboPriceOptions = ref([
  {
    label: ComboPriceNameEnum.ALL,
    value: ''
  },
  {
    label: ComboPriceNameEnum.MONTH,
    value: ComboPriceNameEnum.MONTH
  },
  {
    label: ComboPriceNameEnum.QUARTET,
    value: ComboPriceNameEnum.QUARTET
  },
  {
    label: ComboPriceNameEnum.HALF_YEAR,
    value: ComboPriceNameEnum.HALF_YEAR
  },
  {
    label: ComboPriceNameEnum.YEAR,
    value: ComboPriceNameEnum.YEAR
  }
])

const defaultQueryFields = () => ({
  comboPriceName: comboPriceOptions.value[0].value,
  sellerName: '',
  orderNo: '',
  comboName: '',
  proxyName: '',
  customerName: '',
  orderId: undefined,
  priceAskId: undefined,
  type: TypeEnum.ALL,
  industryCode: undefined,
  payStatus: PayStatusEnum.All,
  serviceStatus: ServiceStatusEnum.All,
  sellerId: mainStore.sellerId,
  customerId: undefined,
  proxyId: mainStore.proxyId,
  keyword: '',
  platformNames: '',
  productId: undefined,
  buyTime: undefined,
  organize: undefined
})

const queryFields = reactive<Partial<OrderQuery>>(defaultQueryFields())
const [, fetchOrderList, loading] = getOrderList()
const [, fetchOrderListWithAll, excelLoading] = getOrderListWithAll()
const [renewalData, fetchOrderRenewal, renewalLoading] = getOrderRenewal()
const [, fetchCalRenewalPrice, caling] = calRenewalPrice()
const [, fetchPriceSheet, submitting] = createPriceSheet()
const [, fetchBwPriceSheet, bwSubmitting] = createBwPriceSheet()
const [, refundAllOrder] = postRefundAllOrder()
const [, refundPartOrder] = postRefundPartOrder()
const [orderKeyword, fetchOrderKeyword] = getOrderKeyword()
const [orderKeywords, orderKeywordByGetitemFn] = orderKeywordByGetitem()
const [industryList, fetchIndustryList] = getIndustryList()
const [, getRenewPriceFn] = getRenewPrice()
const [, getProductListFn] = getProductList()

const columns = computed<TableProps['columns']>(() => {
  return compact([
    {
      title: '订单编号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: '250px'
    },

    {
      title: '大区',
      dataIndex: 'organize',
      key: 'organize',
      width: '150px'
    },
    {
      title: '平台',
      dataIndex: 'platformNames',
      key: 'platformNames',
      width: '150px',
      customRender: ({ text }) => {
        return text || '--'
      }
    },
    {
      title: '关键词',
      dataIndex: 'orderWordsStr',
      key: 'orderWordsStr',
      width: '150px',
      ellipsis: true
    },

    // {
    //   title: '标王编号',
    //   dataIndex: 'zzbwOrderNo',
    //   key: 'zzbwOrderNo',
    //   width: '150px'
    // },
    {
      title: '词包id',
      dataIndex: 'id',
      key: 'id',
      width: '150px'
    },
    {
      title: '查价id',
      dataIndex: 'priceAskId',
      key: 'priceAskId',
      width: '120px'
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: '120px'
    },
    {
      title: '行业',
      dataIndex: 'industryName',
      key: 'industryName',
      width: '150px',
      customRender: ({ text }) => {
        if (!text) {
          return '--'
        }
        return text
      }
    },
    {
      title: '购买套餐',
      dataIndex: 'comboName',
      key: 'comboName',
      width: '200px'
    },
    {
      title: '产品',
      dataIndex: 'productName',
      key: 'productName',
      width: '100px',
      customRender: ({ text }) => {
        return text || '--'
      }
    },
    {
      title: '客户名称',
      dataIndex: 'customerName',
      key: 'customerName',
      width: '200px',
      ellipsis: true
    },
    {
      title: '购买日期',
      dataIndex: 'createTime',
      key: 'createTime',
      width: '200px'
    },
    {
      title: '订单时长',
      dataIndex: 'comboPriceName',
      key: 'comboPriceName',
      width: '150px'
    },
    {
      title: '投放区域',
      dataIndex: 'soldAreas',
      key: 'soldAreas',
      width: '200px'
    },
    {
      title: '状态',
      dataIndex: 'payStatus',
      key: 'payStatus',
      width: '150px',
      customRender: ({ text }: { text: PayStatusEnum }) => {
        return PayStatusKeyMap[text]
      }
    },
    hasPermission([OPERATION, AGENT, AGENT_BOSS, ADMIN]) && {
      title: '销售人员',
      dataIndex: 'sellerName',
      key: 'sellerName',
      width: '150px'
    },
    hasPermission([OPERATION, ADMIN]) && {
      title: '代理商',
      dataIndex: 'proxyName',
      key: 'proxyName',
      width: '270px'
    },
    {
      title: '客户id',
      dataIndex: 'customerId',
      key: 'customerId',
      width: '150px'
    },
    hasPermission([OPERATION, AGENT, AGENT_BOSS, ADMIN]) && {
      title: '市场价',
      dataIndex: 'marketPrice',
      key: 'marketPrice',
      width: '150px',
      customRender: ({ record }: { text: Order }) => {
        if (record.productId === ProductEnum.CiBao || record.productId === ProductEnum.CBYXB) {
          if (record.comboPrice) {
            return record.comboPrice
          } else {
            return '--'
          }
        }

        if (record.marketPrice) {
          return record.marketPrice
        } else if (record.orderPrice) {
          return record.orderPrice
        } else {
          return '--'
        }
      }
    },
    hasPermission([OPERATION, AGENT, AGENT_BOSS, ADMIN]) && {
      title: '提单价',
      dataIndex: 'orderPrice',
      key: 'orderPrice',
      width: '150px'
    },
    hasPermission([OPERATION, AGENT, AGENT_BOSS, ADMIN]) && {
      title: '付款类型',
      dataIndex: 'payType',
      key: 'payType',
      width: '150px',
      customRender: ({ text }: { text: PayTypeEnum }) => {
        return PayTypeKeyMap[text]
      }
    },
    hasPermission([OPERATION, AGENT, AGENT_BOSS, ADMIN]) && {
      title: '折扣',
      dataIndex: 'discount',
      key: 'discount',
      width: '150px'
    },
    hasPermission([OPERATION, AGENT, AGENT_BOSS, ADMIN]) && {
      title: '付款金额',
      dataIndex: 'accountPaidAmount',
      key: 'accountPaidAmount',
      width: '150px'
    },
    hasPermission([OPERATION, AGENT, AGENT_BOSS, ADMIN]) && {
      title: '付款币',
      dataIndex: 'bzCoinPaidAmount',
      key: 'bzCoinPaidAmount',
      width: '150px'
    },
    {
      title: '投放时间段',
      dataIndex: 'onLinePeriod',
      key: 'onLinePeriod',
      width: '150px',
      customRender: ({ record, text }: { record: Order; text: string }) => {
        return text || '--'
      }
    },
    {
      title: '上线状态',
      dataIndex: 'orderStatus',
      key: 'orderStatus',
      width: '150px'
    },
    // {
    //   title: '上线状态',
    //   dataIndex: 'serviceStatus',
    //   key: 'serviceStatus',
    //   width: '150px',
    //   customRender: ({ text }: { text: ServiceStatusEnum }) => {
    //     if (text === ServiceStatusEnum.All) {
    //       return ServiceStatusKeyMap[ServiceStatusEnum.PENDING]
    //     }
    //     return ServiceStatusKeyMap[text]
    //   }
    // },
    // {
    //   title: '落地页',
    //   dataIndex: 'shopType', // LandingPageEnum
    //   key: 'shopType',
    //   width: '150px',
    //   customRender: ({ record }: { record: Order }) => {
    //     return record.shopType === LandingPageEnum.Shop
    //       ? '店铺'
    //       : record.shopType === LandingPageEnum.SinglePage
    //       ? '单页'
    //       : '--'
    //   }
    // },
    // {
    //   title: '黄展转移',
    //   dataIndex: 'hzTransferCode',
    //   key: 'hzTransferCode',
    //   width: '80px',
    //   customRender: ({ record }: { record: Order }) => {
    //     return record.hzTransferCode === IsFromHjzwEnum.Yes ? '是' : '否'
    //   }
    // },
    // {
    //   title: '转移备注',
    //   dataIndex: 'hzNotes',
    //   key: 'hzNotes',
    //   width: '150px'
    // },
    hasPermission([OPERATION, AGENT_BOSS, SALES]) && {
      title: '是否特批',
      dataIndex: 'tpCode',
      key: 'tpCode',
      width: '100px',
      customRender: ({ record }: { record: Order }) => {
        return record.tpCode === IsTPEnum.Yes ? '特批' : '常规'
      }
    },
    // hasPermission([OPERATION, AGENT_BOSS]) && {
    //   title: '类型',
    //   dataIndex: 'tpType',
    //   key: 'tpType',
    //   width: '150px',
    //   ellipsis: true
    // },AGENT_BOSS
    hasPermission([OPERATION]) && {
      title: '特批备注',
      dataIndex: 'tpNotes',
      key: 'tpNotes',
      width: '150px',
      ellipsis: true
    },
    hasPermission([OPERATION, AGENT_BOSS]) && {
      title: '优惠金额',
      dataIndex: 'tpAmount',
      key: 'tpAmount',
      width: '100px',
      ellipsis: true
    },
    {
      title: '上线时间',
      dataIndex: 'serviceTime',
      key: 'serviceTime',
      width: '400px'
    },
    {
      title: '展现预期',
      dataIndex: 'isCancel',
      key: 'isCancel',
      width: '150px'
    },
    // AGENT, ADMIN, SALES
    hasPermission([OPERATION, AGENT_BOSS]) && {
      title: '特批一级类型',
      dataIndex: 'pspecialApproveNames',
      key: 'pspecialApproveNames',
      width: '150px',
      ellipsis: true,
      customRender: ({ text }) => ({
        children: h('span', { class: 'over-hidden' }, text || '--'),
        props: {
          title: text // 鼠标悬停时显示完整内容
        }
      })
    },
    hasPermission([OPERATION, AGENT_BOSS]) && {
      title: '特批二级类型',
      dataIndex: 'specialApproveNames',
      key: 'specialApproveNames',
      width: '150px',
      ellipsis: true,
      customRender: ({ text }) => ({
        children: h('span', { class: 'over-hidden' }, text || '--'),
        props: {
          title: text // 鼠标悬停时显示完整内容
        }
      })
    },
    {
      title: '压缩包',
      dataIndex: 'excelUrl',
      key: 'excelUrl',
      width: '150px'
    },
    {
      title: '压缩包更新时间',
      dataIndex: 'excelUrlTime',
      key: 'excelUrlTime',
      width: '150px'
    },
    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      fixed: 'right',
      width: hasPermission([OPERATION]) ? '360px' : '280px'
    }
  ])
})

const tableData = ref<Order[]>([])

const pagination = reactive({
  current: 1,
  pageSize: 15,
  total: 0
})

async function loadOrderList() {
  const [err, res] = await fetchOrderList({
    pageSize: pagination.pageSize,
    pageNum: pagination.current,
    ...queryFields,
    orderId: queryFields.orderId || 0,
    priceAskId: queryFields.priceAskId || 0,
    customerId: queryFields.customerId || 0,
    industryCode: queryFields.industryCode || 0
  })

  if (!err) {
    pagination.total = res.data.data.totalSize
    tableData.value = res.data.data.orders
  }
}

function resetOrderList() {
  Object.assign(queryFields, defaultQueryFields())
  industryId.value = undefined
  pagination.pageSize = 15
  pagination.current = 1
  selectedFields.value = []
  loadOrderList()
}

function queryOrderList() {
  pagination.pageSize = 15
  pagination.current = 1
  loadOrderList()
}

function handleTableChange(pag: { pageSize: number; current: number }) {
  pagination.pageSize = pag.pageSize
  pagination.current = pag.current
  loadOrderList()
}

function handleDetail(record: Order) {
  orderStore.setCurrentOrderData(record)

  router.push({
    name: 'order-detail'
  })
}

function handleExportExcel(exportExcel: Function) {
  exportExcel(`订单列表${Date.now()}`, {
    payStatus: (value: PayStatusEnum) => PayStatusKeyMap[value],
    payType: (value: PayTypeEnum) => PayTypeKeyMap[value],
    serviceStatus: (value: ServiceStatusEnum) => ServiceStatusKeyMap[value],
    type: (value: TypeEnum) => TypeKeyMap[value]
  })
}

async function handleExportExcelAll(exportExcel: Function) {
  const [err, res] = await fetchOrderListWithAll({
    ...defaultQueryFields(),
    pageNum: 1,
    pageSize: 9999999,
    orderId: queryFields.orderId || 0,
    priceAskId: queryFields.priceAskId || 0,
    customerId: queryFields.customerId || 0,
    industryCode: queryFields.industryCode || 0
  })

  if (err) {
    message.error('导出失败')
  } else {
    exportExcel(
      `订单列表（全部）${Date.now()}`,
      {
        payStatus: (value: PayStatusEnum) => PayStatusKeyMap[value],
        payType: (value: PayTypeEnum) => PayTypeKeyMap[value],
        serviceStatus: (value: ServiceStatusEnum) => ServiceStatusKeyMap[value],
        type: (value: TypeEnum) => TypeKeyMap[value]
      },
      res.data.data.orders
    )
  }
}

function renewalDisabled(record: Order) {
  const { PENDING, Launch } = ServiceStatusEnum
  console.log(record, '续费的禁用', record.serviceStatus)
  if (record.productId === ProductEnum.CiBao || record.productId === ProductEnum.CBYXB) {
    return true
  }
  // console.log('校验的值', isRefund(record) || ![PENDING, Launch].includes(record.serviceStatus)) || ![PENDING, Launch].includes(record.serviceStatus)
  // 退款 或者 不处于待<审核>与<投放中>的订单不能续费
  return isRefunds(record)
}

function handleMenuClick(e: any, record: Order) {
  if (e.key === '1') {
    handleRefundAll(record)
  } else {
    handleRefundPart(record)
  }
}

async function handleRefundAll(record: Order) {
  Modal.confirm({
    title: '提示',
    content: '确定要退全款吗？',
    async onOk() {
      const [err] = await refundAllOrder({
        orderId: record.id
      })

      if (!err) {
        await loadOrderList()
      }
    }
  })
}

async function handleRefundPart(record: Order) {
  Modal.confirm({
    title: '提示',
    content: '确定要退剩余吗？',
    async onOk() {
      const [err] = await refundPartOrder({
        orderId: record.id
      })
      if (!err) {
        await loadOrderList()
      }
    }
  })
}
async function handleRenewalReset() {
  // 重新获取数据
  await fetchOrderRenewal({
    userId: currentRecord.userId,
    orderId: currentRecord.id,
    priceAskId: currentRecord.priceAskId
  })

  // 特殊需求处理
  renewalData.value.approveStatus = ApproveStatusEnum.SUCCESS

  // 重新获取关键词数据
  const [err, res] = await orderKeywordByGetitemFn({
    orderId: currentRecord.id
  })
  if (!err && res) {
    currentOrderKeywords.value = res.data.data
  }

  // 触发变更处理
  handleRenewalChange()
}

const currentOrderKeywords = ref<KeywordData[]>([])
async function handleRenewal(record: Order) {
  renewalDialog.visible = true
  renewalData.value = {}
  currentOrderKeywords.value = []
  Object.assign(currentRecord, record)
  // console.log('点击续费3', record.userId)
  // console.log('点击续费34', record.id)
  // console.log('点击续费35', record.priceAskId)
  await fetchOrderRenewal({
    userId: record.userId,
    orderId: record.id,
    priceAskId: record.priceAskId
  })

  // 特殊需求，测试的时候出现了提单成功后查价审核被改成审核失败的情况
  // 所以在这里要把审核结 果改成成功，不然续费查价会直接提示审核失败
  renewalData.value.approveStatus = ApproveStatusEnum.SUCCESS

  handleRenewalChange()
  const [err, res] = await orderKeywordByGetitemFn({
    orderId: record.id
  })
  if (!err && res) {
    currentOrderKeywords.value = res.data.data
  }

  // const [err, res] = await fetchOrderKeyword({
  //   orderId: record.id
  // })
  // if (!err && res) {
  //   currentOrderKeywords.value = res.data.data
  // }
}

// 是否退款
function isRefund(record: Order) {
  return record.payStatus === PayStatusEnum.Refund
}
function isRefunds(record: Order) {
  return record.payStatus !== 1
}

function handleRefundDisabled(record: Order) {
  const { Launched, Offline } = ServiceStatusEnum

  return isRefund(record) || [Launched, Offline].includes(record.serviceStatus)
}

async function handleRenewalChange(comboPriceName?: ComboPriceNameEnum) {
  let rollback = renewalData.value.comboPriceName
  if (comboPriceName) {
    renewalData.value.comboPriceName = comboPriceName
  }

  // const [err, res] = await fetchCalRenewalPrice({
  //   orderId: oldOrderId(),
  //   rechargeTime: renewalData.value.comboPriceName!
  // })

  // if (!err) {
  //   if (renewalData.value.productId === ProductEnum.BW || renewalData.value.productId === ProductEnum.BWYXB) {
  //     renewalData.value.assessmentPrice = res.data.data.assessRechargePrice
  //     renewalData.value.marketPrice = res.data.data.assessRechargeMarketPriceMarket
  //   }
  // } else {
  //   renewalData.value.comboPriceName = rollback
  // }
}

// 如果对续费订单再做续费操作，则传递最原始的oldOrderId
// 如果是新签订单则oldOrderId就是这个订单的orderId

//20250415 替换成订单id不需要针对原订单续费
function oldOrderId() {
  return currentRecord.id
}
const handdata = ref([])
const handdatas = ref([])
// const handleDataFromChild = (data1: any, data2: any) => {

//   handdata.value = data1
//   handdatas.value = data2
// }
async function handleSubmit() {
  // console.log('需要的数据1', currentOrderKeywords.value)
  // console.log('需要的数据2', renewalData.value)
  // console.log(oldOrderId(), '这个是啥数据啊')

  Modal.confirm({
    title: '提示',
    content: '确定要续费吗？',
    async onOk() {
      let renewMarketPrices = JSON.parse(localStorage.getItem('renewMarketPrices'))
      // console.log(renewMarketPrices, '这个是啥数据啊1')
      // console.log(renewalData.value.productId, '这个是啥数据啊2吗')
      // oldOrderId: renewMarketPrices.oldOrderId,
      //
      let renewMarketPricese = JSON.parse(localStorage.getItem('renewMarketPriceses'))

      if (
        renewalData.value.productId == 2 ||
        renewalData.value.productId == 6 ||
        renewalData.value.productId == 7 ||
        renewalData.value.productId == 10
      ) {
        const [err, res] = await fetchBwPriceSheet({
          // comboPrice

          oldOrderId: oldOrderId(),
          approveStatus: 1,
          // assessmentPrice: renewMarketPrices.data.assessmentPrices,
          areas: JSON.parse(localStorage.getItem('stringArray')),
          // channelPrices: renewalData.value.channelPrices,
          // clientType: 2,
          orderCostRate: renewMarketPricese.orderCostRate ? renewMarketPricese.orderCostRate : null,
          industryCode: renewMarketPricese.industryCode ? renewMarketPricese.industryCode : null,
          premiumRatio: renewMarketPricese.premiumRatio ? renewMarketPricese.premiumRatio : null,
          comboId: renewalData.value.comboId,
          comboName: renewalData.value.comboName,
          comboPrice: renewMarketPricese.comboPrice ? renewMarketPricese.comboPrice : null,
          comboPriceId: renewalData.value.comboPriceId,
          comboPriceName: renewalData.value.comboPriceName,
          mini: renewalData.value.mini,
          moveUp: renewalData.value.moveUp,
          costRate: renewalData.value.costRate,
          hasCreatePic: renewalData.value.hasCreatePic,
          // industryCode: renewMarketPrices.data.subjectCode,
          machineExamine: renewalData.value.machineExamine,
          marketPrice: renewMarketPricese.comboPrice ? renewMarketPricese.comboPrice : null,
          onLinePeriod: renewalData.value.onLinePeriod,

          priceAskWords: renewMarketPricese.priceAskWords,

          productId: renewalData.value.productId,
          proxyId: renewalData.value.proxyId,

          proxyName: renewalData.value.proxyName,
          sellerId: renewalData.value.sellerId,
          sellerName: renewalData.value.sellerName,
          type: 2,
          userArea: renewalData.value.userArea
          // versionType: renewalData.value.versionType
        })

        console.log(err, res, '这个是啥数据啊')
        if (err) {
          message.error(err.message)
        }
        renewalDialog.visible = false
      } else {
        const [err, res] = await fetchBwPriceSheet({
          // orderCostRate: renewMarketPrices.data.orderCostRate ? renewMarketPrices.data.orderCostRate : null,
          industryCode: renewMarketPrices.data.industryCode ? renewMarketPrices.data.industryCode : null,
          premiumRatio: renewMarketPrices.data.premiumRatio ? renewMarketPrices.data.premiumRatio : null,
          renewDiscount: renewMarketPrices.data.renewDiscount ? renewMarketPrices.data.renewDiscount : null,
          orderCostRate: renewMarketPrices.data.orderCostRate ? renewMarketPrices.data.orderCostRate : null,
          renewType: renewMarketPrices.data.renewType,
          oldOrderId: renewMarketPrices.data.oldOrderId,
          approveStatus: renewMarketPrices.data.approveStatus,
          assessmentPrice: renewMarketPrices.data.assessmentPrices,
          areas: JSON.parse(localStorage.getItem('stringArray')),
          channelPrices: renewalData.value.channelPrices,
          clientType: 2,
          comboName: renewalData.value.comboName,
          comboPriceName: renewalData.value.comboPriceName,
          costRate: renewalData.value.costRate,
          hasCreatePic: renewalData.value.hasCreatePic,
          // industryCode: renewMarketPrices.data.subjectCode,
          machineExamine: renewalData.value.machineExamine,
          marketPrice: renewMarketPrices.data.renewMarketPrice,
          onLinePeriod: renewalData.value.onLinePeriod,
          // premiumRatio: renewalData.value.premiumRatio,
          priceAskWords: renewMarketPrices.data.wordAskWords,
          productId: renewalData.value.productId,
          proxyId: renewalData.value.proxyId,
          proxyName: renewalData.value.proxyName,
          sellerId: renewalData.value.sellerId,
          sellerName: renewalData.value.sellerName,
          type: 2,
          userArea: renewalData.value.userArea,
          versionType: renewalData.value.versionType
        })

        console.log(err, res, '这个是啥数据啊')
        if (err) {
          message.error(err.message)
        }
        renewalDialog.visible = false
      }

      // const [err, res] = await fetchBwPriceSheet({
      //   renewDiscount: renewMarketPrices.data.renewDiscount ? renewMarketPrices.data.renewDiscount : null,
      //   orderCostRate: renewMarketPrices.data.orderCostRate ? renewMarketPrices.data.orderCostRate : null,
      //   renewType: renewMarketPrices.data.renewType,
      //   oldOrderId: renewMarketPrices.data.oldOrderId,
      //   approveStatus: renewMarketPrices.data.approveStatus,
      //   assessmentPrice: renewMarketPrices.data.assessmentPrices,
      //   areas: JSON.parse(localStorage.getItem('stringArray')),
      //   channelPrices: renewalData.value.channelPrices,
      //   clientType: 2,
      //   comboName: renewalData.value.comboName,
      //   comboPriceName: renewalData.value.comboPriceName,
      //   costRate: renewalData.value.costRate,
      //   hasCreatePic: renewalData.value.hasCreatePic,
      //   industryCode: renewMarketPrices.data.subjectCode,
      //   machineExamine: renewalData.value.machineExamine,
      //   marketPrice: renewMarketPrices.data.renewMarketPrice,
      //   onLinePeriod: renewalData.value.onLinePeriod,
      //   premiumRatio: renewalData.value.premiumRatio,
      //   priceAskWords: renewMarketPrices.data.wordAskWords,
      //   productId: renewalData.value.productId,
      //   proxyId: renewalData.value.proxyId,
      //   proxyName: renewalData.value.proxyName,
      //   sellerId: renewalData.value.sellerId,
      //   sellerName: renewalData.value.sellerName,
      //   type: 2,
      //   userArea: renewalData.value.userArea,
      //   versionType: renewalData.value.versionType
      // })

      // console.log(err, res, '这个是啥数据啊')
      // if (err) {
      //   message.error(err.message)
      // }
      // renewalDialog.visible = false
    }
  })

  // Modal.confirm({
  //   title: '提示',
  //   content: '确定要续费吗？',
  //   async onOk() {
  //     if (renewalData.value.productId === ProductEnum.BW || renewalData.value.productId === ProductEnum.BWYXB) {
  //       const bwRenewalData = {
  //         ...renewalData.value,
  //         oldOrderId: oldOrderId(),
  //         type: TypeEnum.RENEWAL
  //       }
  //       const valid = bwPriceDataParser().safeParse(bwRenewalData)
  //       // if (!valid.success) {
  //       //   message.error(fromZodError(valid.error).message)
  //       //   return false
  //       // }

  //       const [err] = await fetchBwPriceSheet(bwRenewalData)

  //       if (!err) {
  //         const bw360 = renewalData.value.channelPrices?.find(
  //           (channel) => channel.channelType === ChannelTypeEnum.QiHu360
  //         )

  //         priceSheetStore.setPurchaseData({
  //           selectedData: renewalData.value.priceAskWords!,
  //           BwPriceData: {
  //             comboPriceName: renewalData.value.comboPriceName!,
  //             quote: renewalData.value.onLinePeriod!,
  //             columnName: PlatformKeyMap[renewalData.value.clientType!],
  //             hasCreativePicture: renewalData.value.hasCreatePic,
  //             versionType: renewalData.value.versionType
  //           },
  //           approveStatus: ApproveStatusEnum.PENDING,
  //           Bw360PriceData: bw360 && get360PriceData(bw360.basePriceTypeId),
  //           type: renewalData.value.productId
  //         })
  //         renewalDialog.visible = false

  //         router.push({
  //           name: 'price-purchase'
  //         })
  //       }
  //     } else {
  //       const [err] = await fetchPriceSheet({
  //         ...renewalData.value,
  //         oldOrderId: oldOrderId(),
  //         type: TypeEnum.RENEWAL // 类型属于续费
  //       })

  //       if (!err) {
  //         priceSheetStore.setPurchaseData({
  //           selectedData: renewalData.value.priceAskWords!,
  //           approveStatus: ApproveStatusEnum.PENDING,
  //           CibaoPriceData: {
  //             comboName: renewalData.value.comboName!,
  //             comboPriceName: renewalData.value.comboPriceName!
  //           },
  //           type: renewalData.value.productId
  //         })
  //         renewalDialog.visible = false

  //         router.push({
  //           name: 'price-purchase'
  //         })
  //       }
  //     }
  //   }
  // })
}

function get360PriceData(basePriceTypeId?: number) {
  const data = priceTable.reduce<any[]>((prev, next) => {
    prev.push(...Object.values(next))
    return prev
  }, [])

  const priceData = data.find((d) => {
    return d.priceTypeId === basePriceTypeId
  })

  return {
    quote: `${priceData.onlinePeriodDays}*${priceData.onlinePeriodHours}小时`,
    comboPriceName: BwComboPriceNameKeyMap[`${priceData?.days}天` as ComboPriceTimer],
    columnName: PlatformKeyMap[priceData.clientType as PlatformEnum]
  }
}

//查看账号密码
const visibleshows = ref(false)
const usernameshows = ref('')
const pwdshows = ref('')

const namepwdshows = (a) => {
  console.log(a.username, 'a.password', a.pwd)

  usernameshows.value = a.username
  pwdshows.value = a.pwd

  visibleshows.value = true
}

const handleOkshows = (e) => {
  visibleshows.value = false
}

//修改账号密码
const visiblenamepwe = ref(false)
const formStatenampwe = reactive({
  username: '',
  pwd: '',
  orderId: 0
})
const [, setUserPwdFn] = setUserPwd()
const handleOk = async (e) => {
  console.log(e)
  let [err, res] = await setUserPwdFn(formStatenampwe)
  console.log(err, res, '大运')

  visiblenamepwe.value = false
}

const namepwd = (a) => {
  console.log(a.id, 'a.orderId')
  formStatenampwe.orderId = a.id
  formStatenampwe.username = a.username || ''
  formStatenampwe.pwd = a.pwd || ''
  visiblenamepwe.value = true
}

function handleIndustryChange() {
  queryFields.industryCode = industryList.value.find((item) => item.id === industryId.value)?.code
}

function copySuccess() {
  message.success('复制成功')
}

// 百姓店铺跳转
const [, getShopUrlFn, shopLoading] = getShopUrl()
const [, getShopUrlsFn, shopLoadings] = getShopUrls()
async function jump(record: Order) {
  // console.log(record)
  // if (record.productId === ProductEnum.BWYXB || record.productId === ProductEnum.CBYXB) {
  //   return message.warn('抱歉，优选版店铺尚未开放！')
  // } else {

  // }
  const [err, res] = await getShopUrlsFn({ id: record.id })
  if (!err) {
    const { VITE_HAOJING_API_SECRET, VITE_HAOJING_HOST } = import.meta.env
    const hash = MD5(`${res.data.data}${VITE_HAOJING_API_SECRET}`).toString()
    const url = `${VITE_HAOJING_HOST}?mobile=${res.data.data}&hash=${hash}`
    window.open(url)
  } else {
    message.warn(err.message)
  }
}
// 百搜店铺跳转
async function jumps(record: Order) {
  // console.log(record)
  // if (record.productId === ProductEnum.BWYXB || record.productId === ProductEnum.CBYXB) {
  //   return message.warn('抱歉，优选版店铺尚未开放！')
  // } else {
  // }

  const [err, res] = await getShopUrlFn({ id: record.id })
  if (!err) {
    const phone = res.data.data //通过id获取到手机号
    const { VITE_HAOJING_Hundred_links } = import.meta.env

    const url = `${VITE_HAOJING_Hundred_links}?jumpLogin=${phone}&customerId=${record.customerId}`
    window.open(url)
  } else {
    message.warn(err.message)
  }
}
const shopVisible = ref(false)
const spinning = ref(false)
const loadOption = ref({
  mobile: '',
  customerId: ''
})
const goShop = async (record) => {
  spinning.value = true
  const [err, res] = await getShopUrlsFn({ id: record.id })
  if (!err) {
    loadOption.value.mobile = res.data.data
  }
  if (res.data.code === 0) {
    spinning.value = false
    loadOption.value.customerId = record.customerId
    shopVisible.value = true
  }
}

const linkForm = reactive({
  visible: false,
  value: '',
  orderId: ''
})
const [, orderupFileFn, loadings] = orderupFile()
const [, ordersetExcelUrFn] = ordersetExcelUr()

// 上传excel相关状态
const excelForm = reactive({
  visible: false,
  orderId: '',
  file: null as File | null
})

// 上传excel
const openexcel = async (record) => {
  console.log(record, '点击打开')
  excelForm.visible = true
  excelForm.orderId = record.id
  excelForm.file = null
}
const openexcels = async (record) => {
  if (!record.excelUrl) {
    message.warning('未找到可下载的Excel链接')
    return
  }
  const link = document.createElement('a')
  link.href = record.excelUrl
  link.download = '' // 让浏览器自动用原文件名
  link.target = '_blank'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
// 处理文件选择（兼容 antd vue 2.x/3.x）
const handleFileChange = (info: any) => {
  excelForm.file = info.file?.originFileObj || info.file
}

// 上传文件
const handleUploadExcel = async () => {
  console.log('开始上传文件...')
  if (!excelForm.file) {
    message.warning('请选择要上传的Excel文件')
    return
  }

  console.log('文件信息:', excelForm.file)
  console.log('订单ID:', excelForm.orderId)

  const formData = new FormData()
  formData.append('file', excelForm.file)
  formData.append('orderId', excelForm.orderId.toString())

  console.log('FormData 内容:')
  for (let [key, value] of formData.entries()) {
    console.log(key, value)
  }

  console.log('调用 orderupFileFn...')
  const [err, res] = await orderupFileFn(formData)

  console.log('接口调用结果:', { err, res })

  if (!err) {
    message.success('Excel文件上传成功')
    excelForm.visible = false
    excelForm.file = null
    // 刷新订单列表
    const [errr, ress] = await ordersetExcelUrFn({
      orderId: excelForm.orderId,
      excelUrl: res.data.data
    })
    console.log('接口调用结果111111:', { errr, ress })

    await loadOrderList()
  } else {
    console.error('上传失败:', err)
  }
}

// 关闭上传模态框
const closeExcelModal = () => {
  excelForm.visible = false
  excelForm.file = null
}

const openLinkEdit = (record) => {
  linkForm.visible = true
  linkForm.value = record.linkUrl
  linkForm.orderId = record.id
}

const refreshLinkFn = () => {
  loadOrderList()
}

const onlineForm = reactive({
  visible: false,
  value: [],
  orderId: '',
  orderStatus: '',
  notes: ''
})

const openOnlineEdit = (record) => {
  onlineForm.visible = true
  onlineForm.value = [record.startTime, record.endTime]
  onlineForm.orderId = record.id
  onlineForm.orderStatus = record.orderStatus
  onlineForm.notes = record.notes
}

const refreshOnLineFn = () => {
  loadOrderList()
}

const openLink = (link: string) => {
  if (link) {
    window.open(link, '_blank')
  }
}

// 打开数据报表
const openAirReport = (record: Order) => {
  // 构造参数：orderId字符串 + 真正的orderId
  const paramStr = `orderId${record.id}`
  // Base64编码
  const encodedId = btoa(paramStr)
  // 构造URL
  const url = `/#/aireport/${encodedId}`
  // 在新标签页打开
  window.open(url, '_blank')
}

const initProductList = async () => {
  const [err, res] = await getProductListFn()
  if (!err) {
    // console.log(res.data.data)
    productOptions.value = res.data.data?.map((item) => {
      return {
        value: item.id,
        label: item.name
      }
    })
  }
}

const selectedFields = ref<string[]>([])

const columnOptions = columns.value.map((col) => ({
  label: col.title,
  value: col.dataIndex
}))

const dynamicColumns = computed(() => {
  const cols = Array.isArray(columns.value) ? columns.value : []
  if (!selectedFields.value.length) return cols
  return cols.filter((col) => selectedFields.value.includes(col.dataIndex))
})

const submitInfo = (record) => {
  router.push({
    name: 'order-geo',
    params: {
      orderId: btoa(record.id.toString())
    }
  })
}

onMounted(() => {
  fetchIndustryList()
  initProductList()
})

onActivated(() => {
  loadOrderList()
})

onUnmounted(() => {
  // 清理定时器等资源
})

function downloadTemplate() {
  const url = 'http://geo.e-baixing.com/GEO优化资料填写模版(常规+加码）.xlsx'
  const link = document.createElement('a')
  link.href = url
  link.download = 'GEO优化资料填写模版(常规+加码）.xlsx'
  link.target = '_blank'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
</script>
<style scoped lang="scss">
.over-hidden {
  display: block;
  width: 140px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.load-container {
  min-height: auto !important;
  padding: 0px !important;
}

.ant-modal-body {
  padding: 0px !important;
}

.over-hidden {
  display: block;
  width: 140px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
